<template>
  <el-drawer
    :visible.sync="orderVisible"
    :before-close="handleClose"
    :size="showMobilePage ? '100%' : '80%'"
    title="选择借款审批单">
    <div class="flyUser-list drawer-content">
      <div class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          line-feed
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
      </div>
      <el-tabs v-model="curTabName" style="margin: 17px 0 8px" @tab-click="onSubActiveOrderChange">
        <el-tab-pane label="全部列表" name="all"/>
        <el-tab-pane name="selected">
          <span slot="label">已选择<el-badge v-if="selectedData.length" :value="selectedData.length" /></span>
        </el-tab-pane>
      </el-tabs>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 100px;">
          <el-table
            v-if="(curTabName === 'all' && list.items.length > 0) || (curTabName === 'selected' && selectedData.length > 0)"
            ref="orderDialog"
            :data="curTabName === 'all'?list.items:selectedTableData"
            :height="setTableHeight"
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @sort-change="sortMethod"
            @select="selectTable"
            @select-all="selectTable">
            <el-table-column
              align="center"
              type="selection"
              width="50"
              fixed
            />
            <el-table-column align="left" label="审批单号" min-width="160" fixed>
              <template slot-scope="scope">
                <div class="light-word" @click="toDetail(scope.row)">
                  <ToolTip :content="scope.row.approvalNum"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="借款说明" prop="remark">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.remark"/>
              </template>
            </el-table-column>
            <el-table-column align="right" label="借款金额(元)" min-width="110" prop="amount">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.amount" :price="scope.row.amount / 100" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="借款周期" min-width="200">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.loanStartDate || scope.row.loanEndDate" :open-delay="800" class="item" placement="top" effect="dark">
                  <div slot="content">{{ scope.row.loanStartDate | standardFormat('YYYY/MM/DD') }} - {{ scope.row.loanEndDate | standardFormat('YYYY/MM/DD') }}</div>
                  <div>{{ scope.row.loanStartDate | standardFormat('YYYY/MM/DD') }} - {{ scope.row.loanEndDate | standardFormat('YYYY/MM/DD') }}</div>
                </el-tooltip>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="申请人" prop="applicant">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.applicant" :label="scope.row.applicant" :user-id="scope.row.applicantId" />
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="状态" width="110">
              <template slot-scope="scope">
                <div v-if="scope.row.status">{{ scope.row.status | energyStatus }}</div>
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建人" prop="creator">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="申请部门" prop="applyDepartment">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.applyDepartment"/>
              </template>
            </el-table-column>
            <el-table-column align="left" label="所属部门" prop="subordinateDepartment">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.subordinateDepartment"/>
              </template>
            </el-table-column>
            <el-table-column align="left" label="所属公司">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.company" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建时间" width="160">
              <template slot-scope="scope">
                <div v-if="scope.row.createTime">{{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm') }}</div>
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
          <EmptyPlaceholder v-else style="margin-bottom: 24px" />
        </div>
        <fixed-pagination v-if="curTabName == 'all'" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!hasSeleted" size="small" type="primary" class="related-btn" @click="handleSubmit">{{ btnText }}</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="handleClose">返回</el-button>
          </div>
          <el-pagination
            v-show="list.items.length > 0"
            :current-page="page"
            :page-size="perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
        <fixed-pagination v-if="curTabName == 'selected'" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!hasSeleted" size="small" type="primary" class="related-btn" @click="handleSubmit">{{ btnText }}</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="handleClose">返回</el-button>
          </div>
          <el-pagination
            v-show="selectedData.length > 0"
            :current-page="selectedPage"
            :page-size="selectedPerPage"
            :total="selectedData.length"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>
<script>
// api
import { getLoanList } from '@/api/loan';
import { getDepartmentAll } from '@/api/config';
import { format } from '@/filters/date';
import { paramsRangeFormat } from '@/utils/paramsFormat';
// mixins
import { standardFormat } from '@/filters/date';
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';
import { energyStatus } from '@/filters/status';
import { OUR_TITLE_MODULE } from '@/utils/const';
import { mapState } from 'vuex';

// 组件
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { getModuleOurTitle } from '@/api/invoice';

export default {
  components: {
    EmptyPlaceholder
  },
  filters: {
    standardFormat,
    energyStatus
  },
  mixins: [TableAdaptive, tableSelections],
  props: {
    btnText: {
      type: String,
      default: '确认'
    },
    proposer: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      curTabName: 'all',
      format,
      list: {
        items: [],
        total: 0
      },
      idKey: 'id', // 多选框参数
      tableRefName: 'orderDialog',
      page: 1,
      perPage: 20,
      selectedPage: 1,
      selectedPerPage: 20,
      paramsObj: {},
      listLoading: false,
      deptTreeList: [],
      sortName: '',
      sortType: '',
      orderVisible: false,
      rangeKeyArr: [{
        attr: 'loanDate',
        start: 'loanStartDate',
        end: 'loanEndDate',
        type: 'time',
        addTime: true
      }, {
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time',
        addTime: true
      }, {
        attr: 'amount',
        start: 'amountStart',
        end: 'amountEnd',
        type: 'moneyFixed'
      }],
      selectedData: [],
      tableOutsideHeight: 225,
      departmentOption: [],
      companies: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    hasSeleted() {
      return this.multipleSelectionAll.length > 0;
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'approvalNum', name: '审批单号', labelWidth: '90px', type: 'input' },
        { keyword: 'remark', name: '借款说明', labelWidth: '90px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '90px', type: 'input' },
        { keyword: 'applicant', name: '申请人', labelWidth: '90px', type: 'input' },
        { keyword: 'amount', name: '借款金额', labelWidth: '90px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        // 下拉
        { keyword: 'company', name: '所属公司', type: 'select', valueName: 'label', options: this.companies },
        { keyword: 'applyDepartmentId', name: '申请部门', type: 'cascaderSelectWithChild', childrenVal: 'children',
          options: this.departmentOption },
        { keyword: 'subordinateDepartmentId', name: '所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children',
          options: this.departmentOption },
        { keyword: 'loanDate', name: '借款周期', labelWidth: '90px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '90px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow && this.curTabName === 'all') {
            this.setSelectRow(data.items);
          }
        });
      },
      deep: true
    }
  },
  created() {
    this.queryDeptTreeList();
    this.getCompany();
  },
  methods: {
    openDrawer(list = []) {
      this.$set(this.paramsObj, 'applicant', this.proposer);
      this.fetchData(true);
      this.initData(list);
      this.orderVisible = true;
    },
    initData(list = []) {
      if (!list || list.length === 0) { return; }
      this.selectedData = list;
      this.multipleSelectionAll = list;
      if (this.setSelectRow && this.curTabName === 'all') {
        this.setSelectRow(this.list.items);
      }
    },
    async getCompany() {
      getModuleOurTitle(OUR_TITLE_MODULE.LOAN).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '所属公司'
            });
          });
          this.companies = result;
        }
      });
    },
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.departmentOption = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    handleSubmit() {
      const data = this.selectedData;
      this.$emit('submit', data);
      this.handleClose();
    },
    // 跳转借款单详情
    toDetail(row) {
      const routeUrl = this.$router.resolve({
        name: 'loanDetail',
        query: {
          id: row.id,
          processId: row.processId
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      } else {
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;
      if (this.setSelectRow && this.curTabName === 'selected') this.setSelectRow(this.selectedTableData);
    },
    handleClose() {
      this.orderVisible = false;
      this.multipleSelectionAll = [];
      this.selectedData = [];
      this.curTabName = 'all';
      this.clearMixinSelection && this.clearMixinSelection();
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData(true);
    },
    queryClick() {
      this.curTabName = 'all';
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = '';
      this.fetchData(true);
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.perPage = val;
        this.fetchData(true);
      } else {
        this.selectedPerPage = val;
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.page = toPage;
        this.fetchData();
      } else {
        this.selectedPage = toPage;
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    },
    fetchData(reset = false) {
      this.listLoading = true;
      if (reset) this.page = 1;
      let params = {
        page: this.page,
        perPage: this.perPage,
        tabStatus: this.tabStatus
      };
      params = this.formatParams(params);
      getLoanList(params).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    formatParams(params) {
      const paramsObj = Object.assign({}, this.paramsObj);
      paramsRangeFormat(this.rangeKeyArr, paramsObj);
      Object.keys(paramsObj).forEach(key => {
        if ((paramsObj[key] || paramsObj[key] === 0) && !Array.isArray(paramsObj[key])) {
          params[key] = paramsObj[key];
        }
        if (paramsObj[key] && Array.isArray(paramsObj[key])) {
          params[key] = paramsObj[key].join(',');
        }
      });
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      // params.applicant = this.proposer;
      params.status = 4;// 仅展示已完成的借款单
      return params;
    },
    // 跳转
    toOrderDetail(row = {}) {
      const url = this.$router.resolve({
        name: 'supplierManageDetail',
        query: {
          id: row.id,
          processId: row.processId
        }
      });
      window.open(url.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
.tag-wrap{
  display: flex;
  align-items: center;
}
.tag{
  display: inline-block;
  max-width: 60px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color:#406EFF;
  font-size: 12px;
  padding: 0px 8px;
  background: #eff4ff;
  border-radius: 10px;
  margin-right: 4px;
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  margin-top: 18px;
}
.light-word {
  color: #406eff;
  cursor: pointer;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
        flex:1;
        height: 32px;
        display: flex;
        align-items: center;
        .related-btn {
          margin-left: 20px;
          padding-left: 12px;
          padding-right: 12px;
        }
      }
      ::v-deep .pagination-flex {
        position: absolute;
        width: 100% !important;
      }
      }
    }
    ::v-deep .el-tabs__nav-wrap::after {
      z-index: -1;
    }
    ::v-deep .el-tabs__active-bar {
      bottom: 1px;
    }
</style>
